package com.ncepu.service.Imp;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import com.ncepu.mapper.UserMapper;
import com.ncepu.model.Cachestats;
import com.ncepu.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private Cache<Integer, String> cache;

    @Override
    public String getUserByIdWithCache(int id) {
        String user = cache.getIfPresent(id);
//        System.out.println(cache + "service");
        if(user != null) {
            System.out.println("从缓存中获取用户信息：" + user);
            return user;
        }else {
            user = userMapper.getUserById(id);
            System.out.println("从数据库中获取用户信息：" + user);
            cache.put(id, user);
            return user;
        }
    }

    @Override
    public Cachestats getUserStats() {
        Cachestats cachestats = new Cachestats();
        CacheStats stats = cache.stats();
        System.out.println("命中率" + stats.hitRate());
        cachestats.setHitRate(stats.hitRate());
        System.out.println("平均加载时间" + stats.averageLoadPenalty());
        cachestats.setAverageLoadPenalty(stats.averageLoadPenalty());
        System.out.println("未命中次数" + stats.missCount());
        cachestats.setMissCount(stats.missCount());
        return cachestats;
    }
}
